export function initHeader() {
    // 确保在DOM加载完成后再初始化组件
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initializeHeader);
    } else {
        initializeHeader();
    }
}

function initializeHeader() {
    // 渲染头部组件
    const headerTemplate = `
        <header class="header-content">
            <div class="logo"><i class="ri-tools-fill"></i> 多功能工具箱</div>
            <button id="themeToggle" class="theme-toggle">
                <i class="ri-sun-line light-icon"></i>
                <i class="ri-moon-line dark-icon"></i>
            </button>
        </header>
    `;

    const headerContainer = document.getElementById('headerContainer');
    if (!headerContainer) {
        console.error('Header container not found');
        return;
    }

    headerContainer.innerHTML = headerTemplate;
    initTheme();
    console.log('Header component rendered');
}

// 主题切换功能
function initTheme() {
    const themeToggle = document.getElementById('themeToggle');
    const prefersDarkScheme = window.matchMedia('(prefers-color-scheme: dark)');
    
    // 初始化主题
    const savedTheme = localStorage.getItem('theme');
    if (savedTheme) {
        document.documentElement.setAttribute('data-theme', savedTheme);
    } else if (prefersDarkScheme.matches) {
        document.documentElement.setAttribute('data-theme', 'dark');
    }

    // 切换主题
    const toggleTheme = () => {
        const currentTheme = document.documentElement.getAttribute('data-theme');
        const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
        document.documentElement.setAttribute('data-theme', newTheme);
        localStorage.setItem('theme', newTheme);
        console.log('Theme switched to:', newTheme);
    };

    // 绑定点击事件
    if (themeToggle) {
        themeToggle.addEventListener('click', toggleTheme);
        console.log('Theme toggle button initialized');
    } else {
        console.warn('Theme toggle button not found');
    }

    // 监听系统主题变化
    prefersDarkScheme.addEventListener('change', (e) => {
        if (!localStorage.getItem('theme')) {
            document.documentElement.setAttribute('data-theme', e.matches ? 'dark' : 'light');
        }
    });
}